package org.smart4j.framework;

import org.smart4j.framework.bean.Data;
import org.smart4j.framework.bean.Handler;
import org.smart4j.framework.bean.Param;
import org.smart4j.framework.bean.View;
import org.smart4j.framework.helper.BeanHelper;
import org.smart4j.framework.helper.ConfigHelper;
import org.smart4j.framework.helper.ControllerHelper;
import org.smart4j.framework.util.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2017-12-15
 **/
@WebServlet(urlPatterns = "/*",loadOnStartup = 0)
public class DispatchServlet extends HttpServlet{

    /*
    * 编写一个Servlet，让它来处理所有的请求，从HttpServletRequest对象中获取请求方法与请求路径，通过ControllerHelper.getHandler
    * 方法来获取handler对象
    * 当拿到handler对象后，可以获取Controller类，进而通过BeanHelper.getBean方法获取到Controller的实例对象
    * 随后可以从HttpServletRequest对象中获取所有请求参数，将其初始化到一个名为Param的对象中
    * */

    @Override
    public void init(ServletConfig servletConfig) throws ServletException{
        HelperLoader.init();  //初始化相关helper类
        ServletContext servletContext = servletConfig.getServletContext(); //获取ServletContext对象（用于注册Servlet）
        ServletRegistration jspServlet = servletContext.getServletRegistration("jsp"); //注册处理jsp的servlet
        jspServlet.addMapping(ConfigHelper.getAppJspPath()+"*");
        ServletRegistration defaultServlet = servletContext.getServletRegistration("default");
        defaultServlet.addMapping(ConfigHelper.getAppAssetPath()+"*");
    }

    @Override
    public void service (HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        // 获取请求方法与请求路径
        String requestMethod = request.getMethod().toLowerCase();
        String requestPath = request.getPathInfo();
        //获取Action处理器
        Handler handler = ControllerHelper.getHandler(requestMethod,requestPath);
        if(handler!=null){
            //获取Controller类及其Bean实例
            Class<?> controllerClass = handler.getControllerClass();
            Object controllerBean = BeanHelper.getBean(controllerClass);
            //创建请求参数
            Map<String,Object> paramMap = new HashMap<String , Object>();
            Enumeration<String> paramNames = request.getParameterNames();
            while(paramNames.hasMoreElements()){
                String paraName = paramNames.nextElement();
                String paraValue = request.getParameter(paraName);
                paramMap.put(paraName,paraValue);
            }

            String body = CodecUtil.decodeURL(StreamUtil.getString(request.getInputStream()));
            if(StringUtil.isNotEmpty(body)) {
                String[] params = StringUtil.splitString(body, "&");
                if (ArrayUtil.isNotEmpty(params)) {
                    for (String param : params) {
                        String[] array = StringUtil.splitString(param, "=");
                        if (ArrayUtil.isNotEmpty(array) && array.length == 2) {
                            String paraName = array[0];
                            String paraValue = array[1];
                            paramMap.put(paraName, paraValue);
                        }
                    }
                }
            }
            Param param = new Param(paramMap);
            //调用Action方法
            Method actionMethod = handler.getActionMethod();
            //TODO param参数再查感觉有问题
            Object result = ReflectionUtil.invokeMethod(controllerBean,actionMethod,param);
            //处理Action方法返回值
            if(result instanceof View){
                //返回jsp页面
                View view = (View) result;
                String path = view.getPath();
                if(StringUtil.isNotEmpty(path)){
                    if(path.startsWith("/")){  //以"／"开头说明还是一个action方法，所以接着处理，else才是返回jsp并且带model数据
                        response.sendRedirect(request.getContextPath()+path);
                    } else{
                        Map<String,Object> model = view.getModel();
                        for(Map.Entry<String,Object> entry: model.entrySet()){
                            request.setAttribute(entry.getKey(),entry.getValue());
                        }
                        request.getRequestDispatcher(ConfigHelper.getAppJspPath()+path).forward(request,response);
                    }
                }
            } else if(result instanceof Data){
                Data data = (Data) result;
                Object model = data.getModel();
                if(model!=null){
                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");
                    PrintWriter writer = response.getWriter();
                    String json = JsonUtil.toJson(model);
                    writer.write(json);
                    writer.flush();
                    writer.close();
                }
            }
        }

    }


}
